package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.QaExperts;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.adapter.ExportAdapter;
import com.xudow.app.ui.support.RecyclerViewScrollLocationListener;
import com.xudow.app.ui.support.XLinearLayoutManager;
import com.xudow.app.ui.task.ExportTask;
import com.xudow.app.ui.task.qanda.QuestionSubmitTask;
import com.xudow.app.ui.user.QuestionsActivity;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 我要提问Activity
 *
 * @author lukecheng
 */
public class QandaActivity extends BaseActivity implements ExportAdapter.OnRecyclerViewListener {

    private TextView questionView;

    private RecyclerView exportsRecyclerView;
    private ExportAdapter exportAdapter;
    private List<QaExperts> exports;

    private ExportTask exportTask;
    private QuestionSubmitTask questionSubmitTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qanda);

        questionView = (TextView) findViewById(R.id.question);

        exportsRecyclerView = (RecyclerView) findViewById(R.id.exports);
        exportsRecyclerView.setHasFixedSize(true);

        XLinearLayoutManager layoutManager = new XLinearLayoutManager(this);
        layoutManager.setOnRecyclerViewScrollLocationListener(exportsRecyclerView,
                new RecyclerViewScrollLocationListener() {
                    @Override
                    public void onTopWhenScrollIdle(RecyclerView recyclerView) {
                    }

                    @Override
                    public void onBottomWhenScrollIdle(RecyclerView recyclerView) {
                            // TODO 加载更多
                    }
                });
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        exportsRecyclerView.setLayoutManager(layoutManager);

        exports = new ArrayList<QaExperts>();

        exportAdapter = new ExportAdapter(this, exports);
        exportsRecyclerView.setAdapter(exportAdapter);
        exportAdapter.setOnRecyclerViewListener(this);

        loadExperts();
    }

    /**
     * 获取专家
     */
    private void loadExperts() {
        exportTask = new ExportTask(QandaActivity.this, exportHandler);
        addTask(exportTask);
        exportTask.execute();
    }

    public void onBackBtnClick(View view) {
        if (null != questionSubmitTask && !questionSubmitTask.isCancelled()) {
            questionSubmitTask.cancel(true);
        }

        finish();
    }

    @Override
    public void onItemClick(int position) {  // 专家详情

        QaExperts expert = exports.get(position);

        Intent intent = new Intent(this, ExpertDetailActivity.class);
        intent.putExtra("expertId", expert.getId());
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != questionSubmitTask && !questionSubmitTask.isCancelled()) {
                questionSubmitTask.cancel(true);
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onItemLongClick(int position) {
        return false;
    }

    /**
     * 专家Handler
     */
    private Handler exportHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (ExportTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                QaExperts[] qaExpertses = (QaExperts[]) data.getSerializable("exports");

                if (null == qaExpertses || qaExpertses.length <= 0) {
                    return;
                }

                for (QaExperts expert : qaExpertses) {
                    exports.add(expert);
                }

                exportAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 问题提交按钮事件
     *
     * @param view
     */
    public void onSubmitClick(View view) {
        String question = questionView.getText().toString().trim();

        XApplication application = (XApplication) getApplication();

        if (!application.isLogin()) {
            questionView.setError(getString(R.string.qanda_login_tip));
            return;
        }

        if (TextUtils.isEmpty(question)) {
            questionView.setError(getString(R.string.question_required));
            return;
        }

        HashMap<String, String> params = Maps.newHashMap();
        params.put("question", question);

        showLodingDialog(getString(R.string.submitting));

        questionSubmitTask = new QuestionSubmitTask(this, questionSubmitTaskHandler);
        questionSubmitTask.execute(params);
    }

    /**
     * 新增提问Handler
     */
    private Handler questionSubmitTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (QuestionSubmitTask.SUCCESS == msg.what) {
                questionView.setText("");

                String message = getString(R.string.submit_success);
                Toast.makeText(QandaActivity.this, message, Toast.LENGTH_SHORT).show();
            } else {
                String message = getString(R.string.submit_fail);
                Toast.makeText(QandaActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 已提问点击事件
     *
     * @param view
     */
    public void onAskedClick(View view) {
        XApplication application = (XApplication) getApplication();

        if (!application.isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        } else {
            startActivity(new Intent(this, QuestionsActivity.class));
            finish();
        }
    }
}
